﻿using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AttendanceRecord
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Dictionary<DateTime, SystemStartStopTime> ssstDic = new Dictionary<DateTime, SystemStartStopTime>();
        private List<SystemStartStopTime> ssstList = null;
        private List<string> yearMonthList = new List<string>();
        private List<SystemStartStopTime> currentList = new List<SystemStartStopTime>();
        private string startSystemEventID = "6005";
        private string stopSystemEventID = "6006";
        private void Form1_Load(object sender, EventArgs e)
        {
            this.saveFileDialog1.DefaultExt = "xls";
            this.saveFileDialog1.Filter = "Excel(*.xls)|*.xls";
            this.saveFileDialog1.FileName = "data";

            Version currentVersion = Environment.OSVersion.Version;
            Version compareToVersion = new Version("6.2");
            if (currentVersion.CompareTo(compareToVersion) >= 0)
            {//win8及其以上版本的系统             
                startSystemEventID = "30";
                stopSystemEventID = "7002";
            }
            Task.Factory.StartNew(() =>
            {
                ReadSysLog();
                ssstList = new List<SystemStartStopTime>(ssstDic.Values);
                AutomaticTime(ssstList);
                this.Invoke(new Action(() =>
                {
                    comboBox1.DataSource = yearMonthList;
                    dataGridView1.DataSource = ssstList;
                }));
            }).ContinueWith(t =>
            {
                this.Invoke(new Action(() =>
                {
                    pictureBox1.Visible = false;
                    label1.Visible = false;
                    button1.Enabled = true;
                    comboBox1.Enabled = true;
                }));
            });
            comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var value = comboBox1.Items[comboBox1.SelectedIndex].ToString();
            var list = ssstList.Where(x => x.YearMonth == value).ToList();
            //AutomaticTime(list);
            dataGridView1.DataSource = list;
            currentList = list;
        }
        private SystemStartStopTime GetSystemStartShopTime(DateTime dateTime)
        {
            SystemStartStopTime ssst = null;
            if (ssstDic.ContainsKey(dateTime))
            {
                ssst = ssstDic[dateTime];
            }
            else
            {
                ssst = new SystemStartStopTime();
                ssstDic.Add(dateTime, ssst);
            }
            return ssst;
        }
        private bool IsContainsKeyTime(DateTime datetime)
        {
            return ssstDic.ContainsKey(datetime);
        }
        /// <summary>
        /// 读取系统文档
        /// </summary>
        private void ReadSysLog()
        {
            EventLog myNewLog = new EventLog();
            myNewLog.Log = "System";
            EventLogEntryCollection myCollection = myNewLog.Entries;

            foreach (EventLogEntry item in myCollection)
            {
                DateTime datetime = item.TimeGenerated.Date;
                if (item.EventID.ToString() == startSystemEventID)
                {
                    if (!IsContainsKeyTime(datetime))
                    {
                        var ssst = GetSystemStartShopTime(datetime);
                        ssst.StartTime = item.TimeGenerated;
                        string yearMonthString = item.TimeGenerated.Date.ToString("yyyyMM");
                        ssst.YearMonth = yearMonthString;
                        if (!yearMonthList.Contains(yearMonthString))
                        {
                            yearMonthList.Add(yearMonthString);
                        }
                    }
                }
                if (item.EventID.ToString() == stopSystemEventID)
                {
                    var ssst = GetSystemStartShopTime(datetime);
                    ssst.StopTime = item.TimeGenerated;
                }
            }

        }
        private void ExportExcel()
        {
            //1.创建一个Workbook
            IWorkbook wk = new HSSFWorkbook();

            //2.创建一个工作表Sheet
            ISheet sheet = wk.CreateSheet("工作表1");
            for (int i = 0; i < 4; i++)
            {
                sheet.SetColumnWidth(i, 30 * 256);

            }
            IRow title = sheet.CreateRow(0);
            title.CreateCell(0).SetCellValue("开机时间");
            title.CreateCell(1).SetCellValue("关机时间");
            title.CreateCell(2).SetCellValue("关机时间取整");
            title.CreateCell(3).SetCellValue("加班的时间");

            //3.创建行
            List<SystemStartStopTime> exportList = currentList;
            if (currentList.Count == 0)
                exportList = ssstList;
            for (int i = 0; i < currentList.Count; i++)
            {
                IRow row = sheet.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(currentList[i].StartTime.ToString("yyyy-MM-dd HH:mm:ss"));
                row.CreateCell(1).SetCellValue(currentList[i].StopTime.ToString("yyyy-MM-dd HH:mm:ss"));
                row.CreateCell(2).SetCellValue(currentList[i].ManagedStopTime.ToString("yyyy-MM-dd HH:mm:ss"));
                row.CreateCell(3).SetCellValue(currentList[i].OverTime.ToString());
            }

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (FileStream fs = File.OpenWrite(saveFileDialog1.FileName))
                    {
                        wk.Write(fs);
                        MessageBox.Show("保存成功");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("保存失败查看文件是否占用");
                }

            }

        }
        /// <summary>
        /// 整理时间
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private List<SystemStartStopTime> AutomaticTime(List<SystemStartStopTime> list)
        {
            foreach (var item in list)
            {


                if (item.StopTime.Minute < 30)
                {
                    item.ManagedStopTime = new DateTime(item.StopTime.Year, item.StopTime.Month, item.StopTime.Day, item.StopTime.Hour, 0, 0);
                }
                else
                {
                    item.ManagedStopTime = new DateTime(item.StopTime.Year, item.StopTime.Month, item.StopTime.Day, item.StopTime.Hour, 30, 0);
                }
                //计算加班时间
                System.DayOfWeek dayOfWeek = item.StopTime.DayOfWeek;

                if (dayOfWeek == DayOfWeek.Saturday || dayOfWeek == DayOfWeek.Sunday)
                {
                    TimeSpan overtime = item.StopTime - item.StartTime;
                    int hours = overtime.Hours;
                    int minutes = overtime.Minutes >= 30 ? 30 : 0;
                    TimeSpan ts = new TimeSpan(hours, minutes, 0);
                    item.OverTime = ts;
                }
                else if (item.StopTime.Hour >= 18)
                {
                    DateTime dt = Convert.ToDateTime("17:30");
                    DateTime dt2 = Convert.ToDateTime($"{item.ManagedStopTime.Hour}:{item.ManagedStopTime.Minute}");
                    TimeSpan overTime = dt2 - dt;
                    if (overTime.Hours >= 1)
                    {
                        item.OverTime = overTime;
                    }
                }
            }
            return list;
        }
        private void dataGridView1_MouseEnter(object sender, EventArgs e)
        {
            dataGridView1.Focus();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ExportExcel();
        }

    }
}
